using Domain;
using ErrorCode;
using MediatR;
using SqlSugar;
using System;
using System.Threading;
using System.Threading.Tasks;
using WriteAPI.Command.生产计划;

namespace WriteAPI.CommandHandle.生产计划
{
    /// <summary>
    /// 删除生产计划的扩展命令处理程序
    /// </summary>
    public class DelProductionPlanCommandExtendedHandler : IRequestHandler<DelProductionPlanCommandExtended, APIResult<bool>>
    {
        private readonly ISqlSugarClient _db;

        /// <summary>
        /// 构造函数
        /// </summary>
        public DelProductionPlanCommandExtendedHandler(ISqlSugarClient db)
        {
            _db = db;
        }

        /// <summary>
        /// 处理删除请求
        /// </summary>
        public async Task<APIResult<bool>> Handle(DelProductionPlanCommandExtended request, CancellationToken cancellationToken)
        {
            var result = new APIResult<bool>
            {
                Data = false
            };

            try
            {
                // 先删除相关的物品明细
                await _db.Deleteable<ProductionPlanDetail>()
                    .Where(d => d.PlanId == request.Id)
                    .ExecuteCommandAsync();

                // 删除相关的附件
                await _db.Deleteable<ProductionPlanAttachment>()
                    .Where(a => a.PlanId == request.Id)
                    .ExecuteCommandAsync();

                // 最后删除主表记录
                int deletedCount = await _db.Deleteable<Lwp_ProductionPlan>()
                    .Where(p => p.Id == request.Id)
                    .ExecuteCommandAsync();

                if (deletedCount > 0)
                {
                    result.Success = true;
                    result.Code = 200;
                    result.Message = "删除成功";
                    result.Data = true;
                }
                else
                {
                    result.Success = false;
                    result.Code = 404;
                    result.Message = "未找到要删除的生产计划";
                }
            }
            catch (Exception ex)
            {
                result.Success = false;
                result.Code = 500;
                result.Message = $"删除生产计划失败: {ex.Message}";
            }

            return result;
        }
    }
} 